﻿/* 
Copyright (c) 2009 Ben Combee
Copyright (c) 2008 Chumby Industries

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import com.chumby.util.Delegate;
import com.chumby.util.MCUtil;
import com.chumby.util.xml.XmlUtil;
import com.chumby.widgets.photostrip.Photostrip;



class DropioViewer extends MovieClip
{
	// ==========    Get your own drop.io API Key and place it between the quotes    
	// ==========    http://api.drop.io     
	
	private static var DROPIO_API_KEY = "4197269e1104d166e3f9cbe774b20715d3f6322b";  
	
	// FIXME - make these configurable through Chumby interface
	private static var DROPIO_DROP = "chumbydefault";
	private static var DROPIO_PASSWORD = "";
	
	private var message_txt:TextField;
	private var photos:Photostrip;
	private static var PhotostripDepth:Number = 10;
	private static var MessageDepth:Number = 20;
	private var _xml:XML;
	private var _photoNodes:Array;
	private var _token:String;
	private var _loadedParams:Boolean = false;
	private var _logo: MovieClip;
	
	//-------------------------------------------------------------------
	// MTASC starts with this entry point
	public static function main()
	{
		MCUtil.CreateWithClass(DropioViewer, _root, "main", 1);
	}
	
	//-------------------------------------------------------------------
	public function DropioViewer()
	{
		// If available, get the parameter storage URL from the Chumby web site that is running this configuration widget
		if (_root._chumby_instance_url != undefined) {
			_global._configURL = _root._chumby_instance_url;
			_global._runningWhere = "Chumby configuration web site";
		}
		// Otherwise, if available, get the parameter storage URL if this is running on the Chumby itself
		// Why you would run the configuration widget from the Chumby itself, I have no idea.
		else if (_root._chumby_widget_instance_href != undefined) {
			_global._configURL = _root._chumby_widget_instance_href;
			_global._runningWhere = "Chumby widget";
		}
		// **HERE** Otherwise, use the test url you found using the instructions above
		//else {
		//	_global._configURL = "http://www.chumby.com/xml/widgetinstances/D97D6CFC-ECF4-11DE-BC56-001E681DF646";
		//	_global._runningWhere = "development debugger";
		//}
		
		_logo = _root.attachMovie("DropIoLogo", "logo", MessageDepth + 1, { _x: 80, _y: 92 });
		
		message_txt = this.createTextField("message", MessageDepth, 5, 10, 300, 24);
		photos = MCUtil.CreateWithClass(Photostrip, this, "photostrip", PhotostripDepth);
		//  optional events you can listen for:
		//photos.addEventListener(Photostrip.LOADEDFIRST, Delegate.create(this, firstImageReady));
		//photos.addEventListener(Photostrip.MOVING, Delegate.create(this, hideInfo));
		//photos.addEventListener(Photostrip.STOPPED, Delegate.create(this, showCurrInfo));

		this.showStatus("Loading parameters...", 0xffffff);
		_chumby_get_widget_parameters(Delegate.create(this, DropioViewerStage2));
		setTimeout(Delegate.create(this, DropioViewerStage2), 5000);
	}
		
	public function DropioViewerStage2(params:Object)
	{
		// used to manage timeout from being unable to load configuration paramters
		if (_loadedParams)
			return;
		_loadedParams = true;	
			
		if (params != undefined) {
			if (params["DropIoDropName"] != undefined)
				DROPIO_DROP = params["DropIoDropName"];
			if (params["_private_DropIoPassword"] != undefined)
				DROPIO_PASSWORD = params["_private_DropIoPassword"];
		}
		
		_xml = new XML();
		_xml.ignoreWhite = true;
		_xml.onLoad = Delegate.create(this, gotAssets);

		if(DROPIO_API_KEY == undefined || DROPIO_API_KEY.length == 0) {
			this.showStatus("Missing drop.io API Key", 0xffffff);
			return;
		}
		
		// get the first 30 assets from the drop
		var url:String = "http://api.drop.io/drops/" + DROPIO_DROP +
			"/assets?version=2.0&api_key=" + DROPIO_API_KEY + "&format=xml&order=latest";
		if (DROPIO_PASSWORD != "")
			url = url + "&token=" + DROPIO_PASSWORD;
		_xml.load(url);
		this.showStatus("Loading...", 0xffffff);
	}
	
	//-------------------------------------------------------------------
	private function showStatus(str:String, color:Number)
	{
		message_txt.text = str;
		var my_fmt:TextFormat = new TextFormat();
		my_fmt.color = color;
		my_fmt.size = 15;
		my_fmt.font = "Arial";
		message_txt.setTextFormat(my_fmt);
	}
	
	//-------------------------------------------------------------------
	private function gotAssets(success:Boolean)
	{
		trace(_xml);
		if(success == false)  {
			this.showStatus("Error.", 0xffffff);
			return;
		}
		_photoNodes = XmlUtil.childrenOfType(_xml.firstChild, 'asset');
		if(_photoNodes.length == 0 || _photoNodes.length == undefined) {
			this.showStatus("Cannot find photos", 0xffffff);   // TO DO: check for error code from drop.io
			return;
		}
		this.showStatus("", 0x000000);	// remove "loading..." message

		var images:Array = new Array();
		for (var i:Number=0; i<_photoNodes.length; i++)   {
			var imageData:Object = getNodeData(_photoNodes[i]);
			if (imageData) {
				trace(imageData.path);
				images.push(imageData);
			}
		}

		if (images.length == 0) {
			this.showStatus("Nothing in drop", 0xffffff);
			return;
		}

		_logo.removeMovieClip();

		photos.processImages(images);

	}
	
	//-------------------------------------------------------------------
	private function getNodeData(photoNode:XMLNode):Object
	{
		var statusNode:XMLNode = XmlUtil.firstChildOfType(photoNode, "status");
		var nameNode:XMLNode = XmlUtil.firstChildOfType(photoNode, "title");
		if (!nameNode)
			nameNode = XmlUtil.firstChildOfType(photoNode, "name");
		var typeNode:XMLNode = XmlUtil.firstChildOfType(photoNode, "type");
		var convertedNode:XMLNode = XmlUtil.firstChildOfType(photoNode, "converted");
		var contentsNode:XMLNode = XmlUtil.firstChildOfType(photoNode, "contents");

		if (statusNode && typeNode && (convertedNode || typeNode.firstChild.nodeValue == "note") && nameNode &&
			(statusNode.firstChild.nodeValue == "converted" || typeNode.firstChild.nodeValue == "note")  &&
			(typeNode.firstChild.nodeValue == "image" ||
			 typeNode.firstChild.nodeValue == "audio"||
			 typeNode.firstChild.nodeValue == "note"))
			return { 
				path: convertedNode.firstChild.nodeValue, 
				type: typeNode.firstChild.nodeValue,
				name: nameNode.firstChild.nodeValue,
				contents: contentsNode.firstChild.nodeValue };
		else
			trace('Didn\'t like: ' + typeNode.firstChild.nodeValue);
			return null;
	}

	//-------------------------------------------------------------------

	function _chumby_get_widget_parameters(callback) {
		var _chumby_xml:XML;
		var _chumby_result_xml:XML;
		_global._chumby_xml = new XML();
		_global._chumby_xml.onLoad = function(success) {
			trace("onLoad success: ", success);
			var widget_params = XmlUtil.firstChildOfType(_global._chumby_xml, 'widget_instance');
			widget_params = XmlUtil.firstChildOfType(widget_params,'widget_parameters');
			widget_params = XmlUtil.childrenOfType(widget_params,'widget_parameter');
			var p:Object = {}
			for (var i:String in widget_params) {
				var widget_param = widget_params[i];
				var key:String = XmlUtil.firstChildOfType(widget_param,'name').firstChild.nodeValue;
				var value:String = XmlUtil.firstChildOfType(widget_param,'value').firstChild.nodeValue;
				p[key] = value;
				trace(key + " " + value);
			}
			callback(p);
			//this._chumby_got_widget_parameters(callback, instance);
		}

		this.showStatus("load URL: " + _global._configURL, 0xffffff);
		trace("load URL: " + _global._configURL);
		_global._chumby_xml.load(_global._configURL);
	}
}